<template>
  <div class="dealer-sales">
    <h2>经销商销售额</h2>
    <p>查看各经销商的销售额统计与趋势。</p>
    <table>
      <thead>
        <tr><th>经销商</th><th>本月销售额（元）</th><th>同比增长</th></tr>
      </thead>
      <tbody>
        <tr v-for="d in salesData" :key="d.name">
          <td>{{ d.name }}</td>
          <td>{{ d.amount }}</td>
          <td :style="{color: d.growth >= 0 ? 'green' : 'red'}">
            {{ d.growth >= 0 ? '+' : '' }}{{ d.growth }}%
          </td>
        </tr>
      </tbody>
    </table>
    <div class="chart-line">
      <svg width="100%" height="80" viewBox="0 0 240 80">
        <polyline
          :points="linePoints"
          fill="none"
          stroke="#42b983"
          stroke-width="3"
        />
        <circle v-for="(v, i) in salesTrend" :key="i" :cx="i*35+20" :cy="80-(v.amount-minAmount)*60/rangeAmount" r="4" fill="#42b983" />
      </svg>
      <div class="x-labels">
        <span v-for="(v, i) in salesTrend" :key="i" :style="{left: (i*35+12)+'px'}">{{ v.month }}</span>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
const salesData = ref([])
const salesTrend = ref([])

onMounted(async () => {
  const resSales = await fetch('http://localhost:3001/api/dealer/sales')
  salesData.value = await resSales.json()
  const resTrend = await fetch('http://localhost:3001/api/dealer/sales-trend')
  salesTrend.value = await resTrend.json()
})

const minAmount = computed(() => Math.min(...salesTrend.value.map(v=>v.amount)))
const maxAmount = computed(() => Math.max(...salesTrend.value.map(v=>v.amount)))
const rangeAmount = computed(() => Math.max(1, maxAmount.value-minAmount.value))
const linePoints = computed(() => salesTrend.value.map((v,i)=>`${i*35+20},${80-(v.amount-minAmount.value)*60/rangeAmount.value}`).join(' '))
</script>

<style scoped>
.dealer-sales { padding: 2rem; max-width: 600px; margin: 0 auto; }
table { width: 100%; border-collapse: collapse; margin-top: 1rem; }
th, td { border: 1px solid #ddd; padding: 0.5rem; text-align: left; }
th { background: #f6f8fa; }
.chart-line { position: relative; height: 80px; margin: 1.5rem 0 1rem 0; background: #fff; border-radius: 6px; box-shadow: 0 1px 4px #eee; padding-bottom: 18px; }
.x-labels { position: absolute; bottom: 0; left: 0; width: 100%; font-size: 0.9rem; color: #888; }
.x-labels span { position: absolute; transform: translateX(-50%); }
</style>
